package jaeger

import (
	"com.cyt.common/constant"
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/opentracing/opentracing-go"
	"github.com/uber/jaeger-client-go"
	jaegerConfig "github.com/uber/jaeger-client-go/config"
	"io"
)

func NewJaegerTracer(serviceName string, jaegerHostPort string) (opentracing.Tracer, io.Closer) {

	cfg := &jaegerConfig.Configuration {
		Sampler: &jaegerConfig.SamplerConfig{
			Type  : "const", //固定采样
			Param : 1,       //1=全采样、0=不采样
		},

		Reporter: &jaegerConfig.ReporterConfig{
			LogSpans           : true,
			LocalAgentHostPort : jaegerHostPort,
		},

		ServiceName: serviceName,
	}

	tracer, closer, err := cfg.NewTracer()
	if err != nil {
		panic(fmt.Sprintf("ERROR: cannot init Jaeger: %v\n", err))
	}
	opentracing.SetGlobalTracer(tracer)
	return tracer, closer
}

// 链路追踪
func GfTracer() func(r *ghttp.Request) {
	return func(r *ghttp.Request) {
		tracer, closer := NewJaegerTracer(constant.APP_NAME, g.Cfg().GetString("jaeger.address", "127.0.0.1:6831"))
		defer closer.Close()
		rootSpan := tracer.StartSpan(r.URL.Path)
		defer rootSpan.Finish()
		// 设置请求相关参数
		rootSpan.SetTag("method",r.Method)
		rootSpan.SetTag("url",r.URL.Path)
		traceID := rootSpan.Context().(jaeger.SpanContext).TraceID().String()
		ctx := opentracing.ContextWithSpan(r.Context(), rootSpan)
		r.SetCtx(ctx)
		r.Response.Header().Set("X-Trace-Id", traceID)
		r.Middleware.Next()
		return
	}
}

// 子链路追踪示例
//span, _ := opentracing.StartSpanFromContext(c.Request.Context(), "test")
//defer span.Finish()
//ctx := span.Context().(jaeger.SpanContext)
//span.SetTag("todo","test")